package com.blog.blog.service.impl;

import com.blog.blog.service.SitemapService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.concurrent.TimeUnit;

/**
 * 站点地图服务实现
 */
@Slf4j
@Service
public class SitemapServiceImpl implements SitemapService {

    private final StringRedisTemplate stringRedisTemplate;
    private final com.blog.blog.config.SiteProperties siteProperties;

    public SitemapServiceImpl(StringRedisTemplate stringRedisTemplate, 
                             com.blog.blog.config.SiteProperties siteProperties) {
        this.stringRedisTemplate = stringRedisTemplate;
        this.siteProperties = siteProperties;
    }

    @Override
    public void generateSitemap() {
        try {
            // 设置sitemap生成标记，避免重复生成
            String lockKey = "sitemap:generating";
            Boolean acquired = stringRedisTemplate.opsForValue().setIfAbsent(lockKey, "1", 5, TimeUnit.MINUTES);
            
            if (Boolean.TRUE.equals(acquired)) {
                log.info("开始生成站点地图");
                
                // 清除旧的缓存
                clearSitemapCache();
                
                // 这里可以预生成sitemap内容并缓存，但由于我们的sitemap是动态生成的，
                // 主要是清除缓存让下次访问时重新生成
                
                log.info("站点地图生成完成");
                
                // 异步提交到搜索引擎
                submitSitemapToSearchEngines();
                
            } else {
                log.info("站点地图正在生成中，跳过本次任务");
            }
        } catch (Exception e) {
            log.error("生成站点地图失败", e);
        }
    }

    @Override
    public void clearSitemapCache() {
        try {
            // 清除sitemap相关的缓存
            stringRedisTemplate.delete("sitemap:*");
            log.info("站点地图缓存已清除");
        } catch (Exception e) {
            log.error("清除站点地图缓存失败", e);
        }
    }

    @Override
    @Async
    public void submitSitemapToSearchEngines() {
        String baseUrl = siteProperties.getBaseUrl();
        if (baseUrl == null || baseUrl.isBlank()) {
            log.warn("未配置网站基础URL，跳过搜索引擎提交");
            return;
        }

        String sitemapUrl = baseUrl.replaceAll("/$", "") + "/sitemap.xml";
        
        // 提交到Google
        submitToGoogle(sitemapUrl);
        
        // 提交到Bing
        submitToBing(sitemapUrl);
        
        // 提交到百度
        submitToBaidu(sitemapUrl);
    }

    private void submitToGoogle(String sitemapUrl) {
        try {
            String submitUrl = "https://www.google.com/ping?sitemap=" + sitemapUrl;
            HttpClient client = HttpClient.newBuilder()
                    .connectTimeout(Duration.ofSeconds(10))
                    .build();
            
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create(submitUrl))
                    .timeout(Duration.ofSeconds(30))
                    .GET()
                    .build();
            
            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
            
            if (response.statusCode() == 200) {
                log.info("成功提交站点地图到Google: {}", sitemapUrl);
            } else {
                log.warn("提交站点地图到Google失败，状态码: {}", response.statusCode());
            }
        } catch (IOException | InterruptedException e) {
            log.error("提交站点地图到Google时发生错误", e);
        }
    }

    private void submitToBing(String sitemapUrl) {
        try {
            String submitUrl = "https://www.bing.com/ping?sitemap=" + sitemapUrl;
            HttpClient client = HttpClient.newBuilder()
                    .connectTimeout(Duration.ofSeconds(10))
                    .build();
            
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create(submitUrl))
                    .timeout(Duration.ofSeconds(30))
                    .GET()
                    .build();
            
            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
            
            if (response.statusCode() == 200) {
                log.info("成功提交站点地图到Bing: {}", sitemapUrl);
            } else {
                log.warn("提交站点地图到Bing失败，状态码: {}", response.statusCode());
            }
        } catch (IOException | InterruptedException e) {
            log.error("提交站点地图到Bing时发生错误", e);
        }
    }

    private void submitToBaidu(String sitemapUrl) {
        try {
            // 百度的sitemap提交需要在百度站长平台手动提交
            // 这里只是记录日志，实际需要手动操作
            log.info("请手动在百度站长平台提交站点地图: {}", sitemapUrl);
        } catch (Exception e) {
            log.error("处理百度站点地图提交时发生错误", e);
        }
    }

    /**
     * 定时任务：每天凌晨2点生成站点地图
     */
    @Override
    @Scheduled(cron = "0 0 2 * * ?")
    public void scheduledGenerateSitemap() {
        log.info("执行定时任务：生成站点地图");
        generateSitemap();
    }

    /**
     * 定时任务：每周一凌晨3点提交站点地图到搜索引擎
     */
    @Override
    @Scheduled(cron = "0 0 3 * * MON")
    public void scheduledSubmitSitemap() {
        log.info("执行定时任务：提交站点地图到搜索引擎");
        submitSitemapToSearchEngines();
    }
}
